package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.user.ILoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.UserConverterMapper;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dto.CheckAuthRequest;
import com.mall.user.dto.CheckAuthResponse;
import com.mall.user.dto.UserLoginRequest;
import com.mall.user.dto.UserLoginResponse;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;

/**
 * @Author：Chunk
 * @Description:
 * @Date Created in 20:22 2021/4/21
 */
@Slf4j
@org.apache.dubbo.config.annotation.Service
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserConverterMapper userConverterMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest userLoginRequest) {
        UserLoginResponse userLoginResponse1 = null;
        try {
            UserLoginResponse userLoginResponse = new UserLoginResponse();
            //判空验证
            userLoginRequest.requestCheck();
            //验证账号和密码是否正确
            //password通过md5加密处理
            String userPassword = DigestUtils.md5DigestAsHex(userLoginRequest.getPassword().getBytes());
            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("username", userLoginRequest.getUserName())
                    .andEqualTo("password",userPassword);
            List<Member> members = memberMapper.selectByExample(example);
            if(CollectionUtils.isEmpty(members)){
                userLoginResponse.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
                userLoginResponse.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
                return userLoginResponse;
            }

            //判断该账号是否激活
            Member member = members.get(0);
            if("N".equals(member.getIsVerified())){
                userLoginResponse.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
                userLoginResponse.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
                return userLoginResponse;
            }
            //利用JWT生成token
            HashMap<String, Object> map = new HashMap<>();
            map.put("uid", member.getId());
            map.put("file", member.getFile());
            map.put("username", member.getUsername());
            String token = JwtTokenUtils.builder().msg(JSON.toJSONString(map)).build().creatJwtToken();

            //将do转换为dto
            userLoginResponse1 = userConverterMapper.converter(member);
            userLoginResponse1.setToken(token);
            userLoginResponse1.setCode(SysRetCodeConstants.SUCCESS.getCode());
            userLoginResponse1.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(userLoginResponse1,e);
        }
        return userLoginResponse1;
    }

    @Override
    public CheckAuthResponse validLogin(CheckAuthRequest checkAuthRequest) {
        CheckAuthResponse checkAuthResponse = new CheckAuthResponse();

        try {
            //判空验证
            checkAuthRequest.requestCheck();
            //解析token
            String msg = JwtTokenUtils.builder().token(checkAuthRequest.getToken()).build().freeJwt();
            HashMap map = JSONObject.parseObject(msg, HashMap.class);
            Integer uid = (Integer) map.get("uid");
            String file = (String)map.get("file");
            checkAuthResponse.setUid(uid);
            checkAuthResponse.setFile(file);
            checkAuthResponse.setUserInfo(msg);
            checkAuthResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            log.info("token解析成功");
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(checkAuthResponse,e);
        }
        return checkAuthResponse;
    }
}
